package com.hethongviet.vendingmobi;

import org.json.JSONArray;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.hethongviet.library.common.Utils;
import com.hethongviet.library.model.Transaction;
import com.hethongviet.library.msg.DialogMessageBack;
import com.hethongviet.library.network.OnNetworkHandleListener;
import com.hethongviet.vendingmobi.helpers.Network;
import com.hethongviet.vendingmobi.model.Account;

public class PageLoginActivity extends OnNetworkHandleListener
{

	private EditText mLoginTextUsername = null;
	private EditText mLoginTextPassword = null;
	private EditText mLoginTextMachineCode = null;
	private Button mLoginButtonLogin = null;

	private Account mAccount = null;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		setContentView(R.layout.page_login);

		mLoginTextUsername = (EditText) findViewById(R.id.login_text_username);
		mLoginTextPassword = (EditText) findViewById(R.id.login_text_password);
		mLoginTextMachineCode = (EditText) findViewById(R.id.login_text_machine_code);
		mLoginButtonLogin = (Button) findViewById(R.id.login_button_login);

		if (Config.IS_DEBUG)
		{
			mLoginTextMachineCode.setText("VM001");
//			mLoginTextUsername.setText("ngoctan");
//			mLoginTextPassword.setText("ngoctan12");
			
			mLoginTextUsername.setText("tuanvtools");
			mLoginTextPassword.setText("phuong12tu");
		}

		mLoginButtonLogin.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View arg0)
			{
				String password = mLoginTextPassword.getText().toString();
				if (password == null || password.equals(""))
				{
					try
					{
						showDialog(R.string.message_error_login_must_input_password);
					} catch (Exception e)
					{
						e.printStackTrace();
					}

					return;
				}
				for (int index = 0; index < password.length(); index++)
				{
					char c = password.charAt(index);

					if (!Character.isLetterOrDigit(c))
					{
						showDialogWithCatch(R.string.message_error_wrong_input_password);
						return;
					}
				}

				if (password.length() < Constants.LENGTH_MIN_PASSWORD)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_password);
					return;
				}

				if (password.length() > Constants.LENGTH_MAX_PASSWORD)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_password);
					return;
				}

				String username = mLoginTextUsername.getText().toString();
				if (username == null || username.equals(""))
				{
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				for (int index = 0; index < username.length(); index++)
				{
					char c = username.charAt(index);

					if (!Character.isLetterOrDigit(c) && c != '_' && c != '-'
							&& c != ' ')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_name);
						return;
					}
				}

				if (username.length() < Constants.LENGTH_MIN_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_name);
					return;
				}

				if (username.length() > Constants.LENGTH_MAX_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_name);
					return;
				}

				String machineCode = mLoginTextMachineCode.getText().toString();
				if (machineCode == null || machineCode.equals(""))
				{
					showDialogWithCatch(R.string.message_error_input_null);
					return;
				}

				for (int index = 0; index < machineCode.length(); index++)
				{
					char c = machineCode.charAt(index);

					if (!Character.isLetterOrDigit(c) && c != '_' && c != '-'
							&& c != ' ')
					{
						showDialogWithCatch(R.string.message_error_wrong_input_name);
						return;
					}
				}

				if (machineCode.length() < Constants.LENGTH_MIN_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_short_name);
					return;
				}

				if (machineCode.length() > Constants.LENGTH_MAX_NAME)
				{
					showDialogWithCatch(R.string.message_error_input_too_long_name);
					return;
				}

				Network.sendRequestLogin(machineCode, username, password);

				mAccount = new Account();
				mAccount.setUsername(username);
				mAccount.setPassword(password);
				mAccount.setName(machineCode);

				Utils.showProgress(PageLoginActivity.this,
						getString(R.string.please_wait));
			}
		});

	}

	@Override
	protected void onResume()
	{

		Network.setOnNetworkHandleListener(this);
		super.onResume();
	}

	@Override
	protected Dialog onCreateDialog(int id)
	{
		if (id == R.string.message_error_input_too_long_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_NUMBER), false);
		}
		else if (id == R.string.message_error_input_too_short_number)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_NUMBER), false);
		}
		else if (id == R.string.message_error_input_too_long_password)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MAX_PASSWORD), false);
		}
		else if (id == R.string.message_error_input_too_short_password)
		{
			return new DialogMessageBack(this, true, String.format(
					getString(id), Constants.LENGTH_MIN_PASSWORD), false);
		}
		else
		{
			return createDialogStatusServer(id);
		}
	}

	@Override
	public void onConnectFail(int typeError)
	{
		runOnUiThread(new Runnable()
		{

			@Override
			public void run()
			{
				Utils.hideProgressDialog();
			}
		});
	}

	@Override
	public void onNetworkMessageIncomming(final Transaction transaction)
	{
		runOnUiThread(new Runnable()
		{
			@Override
			public void run()
			{

				if (transaction.getMethodSent().equals(Constants.LOGIN))
				{
					if (transaction.getMessageReceived().contains(
							Constants.RESULT_OK))
					{
						mAccount.setPermitAccess(Account.PERMIT_CUSTOMER);
						
						String[] strings = transaction.getMessageReceived()
								.split("[:]");

						if (strings != null && strings.length > 1)
						{
							if (strings[1]
									.equals(Constants.PERMISSION_ACCOUNT_ADMIN))
							{
								mAccount.setPermitAccess(Account.PERMIT_ADMIN);
							}
							else if (strings[1]
									.equals(Constants.PERMISSION_ACCOUNT_OWNER))
							{
								mAccount.setPermitAccess(Account.PERMIT_OWNER);
							}
							else if (strings[1]
									.equals(Constants.PERMISSION_ACCOUNT_VENDOR))
							{
								mAccount.setPermitAccess(Account.PERMIT_VENDER);
							}
						}

						Network.sendRequestGetBoxes(mAccount);
					}
					else
					{
						if (transaction.getMessageReceived()
								.contains("machine"))
						{
							showDialogWithCatch(R.string.message_error_login_fail_wrong_machine_code);
						}
						else
						{
							showDialogWithCatch(R.string.message_error_login_fail);
						}
					}
				}
				else if (transaction.getMethodSent().equals(
						Constants.GET_BOX_INVENTORY))
				{
					if (!transaction.getMessageReceived().equals(""))
					{
						// String stringMessage =
						// "[{\"BoxNumber\":\"1\",\"ProductCode\":\"17928\",\"RemainQuantity\":\"8978\"},"
						// +
						// "{\"BoxNumber\":\"2\",\"ProductCode\":\"17930\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"3\",\"ProductCode\":\"17930\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"4\",\"ProductCode\":\"17937\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"5\",\"ProductCode\":\"17950\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"6\",\"ProductCode\":\"52153\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"8\",\"ProductCode\":\"17950\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"7\",\"ProductCode\":\"52153\",\"RemainQuantity\":\"0\"},"
						// +
						// "{\"BoxNumber\":\"9\",\"ProductCode\":\"52153\",\"RemainQuantity\":\"0\"}]";

						try
						{
							new JSONArray(transaction.getMessageReceived());

							Intent intent = new Intent(PageLoginActivity.this,
									PageMainActivity.class);

							Bundle bundle = new Bundle();
							bundle.putString(Constants.EXTRA_BOX_INVENTORY,
									transaction.getMessageReceived());
							bundle.putSerializable(Constants.EXTRA_ACCOUNT,
									mAccount);

							intent.putExtras(bundle);
							startActivity(intent);

						} catch (Exception e)
						{
							showDialogWithCatch(R.string.message_server_send_fail_db);
							e.printStackTrace();
						}
					}
				}

				Utils.hideProgressDialog();
			}
		});

	}

}
